﻿using System.Security.Cryptography;
using System.Text;

namespace MiserBlogHelper.Helper
{
    public class StrHelper
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Encrypt(string str)
        {
            byte[] bs = Encoding.Default.GetBytes(str);
            byte b1, b2;
            StringBuilder sb = new StringBuilder();
            foreach (var b in bs)
            {
                b1 = (byte)(b / 10);
                b2 = (byte)(b % 10);

                sb.Append(b1.ToString("x2"));
                sb.Append(b2.ToString("x2"));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Decrypt(string str)
        {
            string s = string.Empty;
            byte[] bs = new byte[str.Length / 4];
            int index = 0;
            for (int i = 0; i < str.Length; i++, index++)
            {
                byte byteStr1 = byte.Parse(str[i].ToString() + str[++i].ToString(), System.Globalization.NumberStyles.HexNumber);
                byte byteStr2 = byte.Parse(str[++i].ToString() + str[++i].ToString(), System.Globalization.NumberStyles.HexNumber);

                byte b = (byte)(byteStr1 * 10 + byteStr2);
                bs[index] = b;
            }

            str = System.Text.Encoding.Default.GetString(bs);
            return str;
        }

        public static string CutEnd(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return str.Substring(0, str.Length - 1);
            }
            return string.Empty;
        }
    }
}
